'use client';

// 批量导入对话框组件
// REF: API-SHARE189-004@v1.0

import React, { useState } from 'react';
import {
  Upload,
  RefreshCw,
  FileText,
  CheckCircle,
  XCircle,
  AlertCircle,
  PackageOpen,
  Zap,
  Info
} from 'lucide-react';

import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import { useToast } from '@/hooks/use-toast';
import { ImportApiService } from './api';

interface BatchImportDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onRefresh: () => void;
}

interface ParseResult {
  shareCodes: string[];
  accessCodes: string[];
  suggestions: {
    shareCode: string;
    accessCode?: string;
    description: string;
  }[];
}

interface ImportResult {
  addedCount: number;
  skippedCount: number;
  errorCount: number;
  errors: string[];
  message: string;
}

export function BatchImportDialog({ 
  open, 
  onOpenChange, 
  onRefresh 
}: BatchImportDialogProps) {
  const { toast } = useToast();
  const [importText, setImportText] = useState('');
  const [parseResult, setParseResult] = useState<ParseResult | null>(null);
  const [importResult, setImportResult] = useState<ImportResult | null>(null);
  const [parsing, setParsing] = useState(false);
  const [importing, setImporting] = useState(false);
  const [step, setStep] = useState<'input' | 'preview' | 'result'>('input');

  const handleParseText = async () => {
    if (!importText.trim()) {
      toast({
        title: '请输入内容',
        description: '导入内容不能为空',
        variant: 'destructive'
      });
      return;
    }
    
    setParsing(true);
    try {
      const result = await ImportApiService.parseTextForShareCodes({
        text: importText,
        extractAccessCodes: true
      });
      
      setParseResult(result);
      setStep('preview');
      
      toast({
        title: '解析完成',
        description: `识别到 ${result.shareCodes.length} 个分享码`
      });
    } catch (error: any) {
      toast({
        title: '解析失败',
        description: error.message || '请检查输入内容',
        variant: 'destructive'
      });
    } finally {
      setParsing(false);
    }
  };

  const handleBatchImport = async () => {
    if (!parseResult || parseResult.suggestions.length === 0) return;
    
    setImporting(true);
    try {
      const result = await ImportApiService.batchAddShareCodes({
        shareCodes: parseResult.suggestions
      });
      
      setImportResult(result);
      setStep('result');
      
      toast({
        title: '导入完成',
        description: result.message
      });
      
      // 刷新列表
      onRefresh();
    } catch (error: any) {
      toast({
        title: '导入失败',
        description: error.message || '请稍后重试',
        variant: 'destructive'
      });
    } finally {
      setImporting(false);
    }
  };

  const handleClose = () => {
    setImportText('');
    setParseResult(null);
    setImportResult(null);
    setStep('input');
    onOpenChange(false);
  };

  const handleStartOver = () => {
    setParseResult(null);
    setImportResult(null);
    setStep('input');
  };

  return (
    <Dialog open={open} onOpenChange={handleClose}>
      <DialogContent className="max-w-5xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="text-xl flex items-center gap-2">
            <PackageOpen className="h-6 w-6 text-blue-600" />
            批量导入分享码
            <Badge variant="secondary" className="ml-2 bg-green-100 text-green-700 border-green-200">
              <Zap className="h-3 w-3 mr-1" />
              推荐
            </Badge>
            <Badge variant="outline" className="ml-2">
              {step === 'input' && '步骤 1/3: 输入文本'}
              {step === 'preview' && '步骤 2/3: 预览确认'}
              {step === 'result' && '步骤 3/3: 导入结果'}
            </Badge>
          </DialogTitle>
        </DialogHeader>
        
        <div className="space-y-6">
          {/* 步骤1: 输入文本 */}
          {step === 'input' && (
            <Card>
              <CardHeader>
                <CardTitle className="text-lg flex items-center gap-2">
                  <FileText className="h-5 w-5 text-blue-600" />
                  输入分享码文本
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                  <div className="flex items-start gap-2">
                    <Info className="h-5 w-5 text-blue-600 mt-0.5 flex-shrink-0" />
                    <div className="text-sm text-blue-800">
                      <div className="font-medium mb-1">支持的格式：</div>
                      <ul className="list-disc list-inside space-y-1 text-blue-700">
                        <li>完整链接：https://cloud.189.cn/t/abc123def 访问码：1234</li>
                        <li>分享码格式：分享码：abc123def 提取码：1234</li>
                        <li>混合文本：支持从任意文本中自动提取分享码和访问码</li>
                      </ul>
                    </div>
                  </div>
                </div>
                
                <div className="space-y-2">
                  <Label htmlFor="importText">导入内容</Label>
                  <Textarea
                    id="importText"
                    placeholder="粘贴包含分享链接的文本，系统会自动识别分享码和访问码\n\n支持格式示例：\n• https://cloud.189.cn/t/abc123def 访问码：1234\n• 分享码：abc123def 提取码：1234\n• 链接: https://cloud.189.cn/t/xyz789uvw\n• 或直接粘贴包含多个链接的文本"
                    value={importText}
                    onChange={(e) => setImportText(e.target.value)}
                    rows={8}
                    className="resize-none"
                  />
                </div>
                
                <div className="flex items-center gap-3">
                  <Button 
                    onClick={handleParseText}
                    disabled={parsing || !importText.trim()}
                    className="flex items-center gap-2 bg-blue-600 hover:bg-blue-700"
                    size="lg"
                  >
                    {parsing ? (
                      <RefreshCw className="h-4 w-4 animate-spin" />
                    ) : (
                      <FileText className="h-4 w-4" />
                    )}
                    {parsing ? '解析中...' : '解析文本'}
                  </Button>
                  
                  <div className="text-sm text-gray-500">
                    支持天翼云分享链接自动识别和访问码提取
                  </div>
                </div>
              </CardContent>
            </Card>
          )}
          
          {/* 步骤2: 预览确认 */}
          {step === 'preview' && parseResult && (
            <Card>
              <CardHeader>
                <CardTitle className="text-lg flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <FileText className="h-5 w-5 text-green-600" />
                    解析结果预览
                  </div>
                  <Badge variant="outline" className="bg-green-50 text-green-700 border-green-200">
                    识别到 {parseResult.shareCodes.length} 个分享码
                  </Badge>
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                  <div className="text-sm text-blue-700">
                    识别到 <strong>{parseResult.shareCodes.length}</strong> 个分享码，
                    <strong>{parseResult.accessCodes.length}</strong> 个访问码
                  </div>
                </div>
                
                {parseResult.suggestions.length > 0 ? (
                  <div className="border rounded-lg">
                    <div className="p-3 border-b bg-gray-50">
                      <h5 className="font-medium text-sm text-gray-900">待导入的分享码</h5>
                    </div>
                    <div className="max-h-60 overflow-y-auto">
                      {parseResult.suggestions.map((suggestion, index) => (
                        <div key={index} className="p-3 border-b last:border-b-0 hover:bg-gradient-to-r hover:from-blue-50 hover:to-green-50">
                          <div className="flex items-start justify-between">
                            <div className="flex-1">
                              <div className="font-mono text-sm font-medium text-blue-600">
                                {suggestion.shareCode}
                              </div>
                              {suggestion.accessCode && (
                                <div className="text-xs text-gray-500 mt-1">
                                  访问码: <span className="font-mono bg-green-100 text-green-700 px-1 rounded">{suggestion.accessCode}</span>
                                </div>
                              )}
                              <div className="text-xs text-gray-400 mt-1">
                                {suggestion.description}
                              </div>
                            </div>
                            <Badge variant="outline" className="text-xs bg-blue-100 text-blue-700 border-blue-300">
                              #{index + 1}
                            </Badge>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                ) : (
                  <div className="text-center py-12 text-gray-500">
                    <XCircle className="h-16 w-16 mx-auto mb-4 text-gray-400" />
                    <div className="text-lg font-medium mb-2">未找到有效的分享码</div>
                    <div className="text-sm">请检查输入的文本格式是否正确</div>
                  </div>
                )}
                
                <Separator />
                
                <div className="flex items-center gap-3">
                  <Button 
                    onClick={handleBatchImport}
                    disabled={importing || parseResult.suggestions.length === 0}
                    className="flex items-center gap-2 bg-green-600 hover:bg-green-700"
                    size="lg"
                  >
                    {importing ? (
                      <RefreshCw className="h-4 w-4 animate-spin" />
                    ) : (
                      <Upload className="h-4 w-4" />
                    )}
                    {importing ? '导入中...' : `导入 ${parseResult.suggestions.length} 个分享码`}
                  </Button>
                  
                  <Button 
                    variant="outline"
                    onClick={handleStartOver}
                    disabled={importing}
                  >
                    重新输入
                  </Button>
                </div>
              </CardContent>
            </Card>
          )}
          
          {/* 步骤3: 导入结果 */}
          {step === 'result' && importResult && (
            <Card>
              <CardHeader>
                <CardTitle className="text-lg flex items-center gap-2">
                  <CheckCircle className="h-5 w-5 text-green-600" />
                  导入结果
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                {/* 结果统计 */}
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  <div className="bg-green-50 border border-green-200 rounded-lg p-4">
                    <div className="flex items-center gap-2 text-green-700">
                      <CheckCircle className="h-5 w-5" />
                      <span className="font-medium">成功添加</span>
                    </div>
                    <div className="text-2xl font-bold text-green-900 mt-1">
                      {importResult.addedCount}
                    </div>
                  </div>
                  
                  <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                    <div className="flex items-center gap-2 text-yellow-700">
                      <AlertCircle className="h-5 w-5" />
                      <span className="font-medium">已跳过</span>
                    </div>
                    <div className="text-2xl font-bold text-yellow-900 mt-1">
                      {importResult.skippedCount}
                    </div>
                  </div>
                  
                  <div className="bg-red-50 border border-red-200 rounded-lg p-4">
                    <div className="flex items-center gap-2 text-red-700">
                      <XCircle className="h-5 w-5" />
                      <span className="font-medium">失败</span>
                    </div>
                    <div className="text-2xl font-bold text-red-900 mt-1">
                      {importResult.errorCount}
                    </div>
                  </div>
                </div>
                
                {/* 错误详情 */}
                {importResult.errors.length > 0 && (
                  <div className="border border-red-200 rounded-lg">
                    <div className="p-3 border-b bg-red-50">
                      <h5 className="font-medium text-sm text-red-900">错误详情</h5>
                    </div>
                    <div className="max-h-40 overflow-y-auto p-3">
                      {importResult.errors.map((error, index) => (
                        <div key={index} className="text-sm text-red-700 mb-1">
                          • {error}
                        </div>
                      ))}
                    </div>
                  </div>
                )}
                
                {/* 结果消息 */}
                <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                  <div className="text-sm text-blue-700">
                    {importResult.message}
                  </div>
                </div>
                
                <Separator />
                
                <div className="flex items-center gap-3">
                  <Button 
                    onClick={handleClose}
                    className="flex items-center gap-2 bg-blue-600 hover:bg-blue-700"
                    size="lg"
                  >
                    <CheckCircle className="h-4 w-4" />
                    完成
                  </Button>
                  
                  <Button 
                    variant="outline"
                    onClick={handleStartOver}
                  >
                    继续导入
                  </Button>
                </div>
              </CardContent>
            </Card>
          )}
        </div>
      </DialogContent>
    </Dialog>
  );
}

export default BatchImportDialog;